<?php
/**
 * Here is your custom functions.
 */

// 屏蔽通知错误
use Webman\Http\Request;

error_reporting(E_ALL ^ E_NOTICE);

function apiSuccess(array $data = [])
{
    $res = [
        'code' => \app\common\enum\ErrorCode::SUCCESS,
        'msg'  => 'ok',
    ];
    if ($data) {
        $res['data'] = $data;
    }
    return $res;
}


/**
 * 返回带协议的域名
 * @author rainfer <81818832@qq.com>
 */
function get_host(){
    $host = \request()->host();
    $protocol= (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ?"https://":"http://";
    return $protocol.$host;
}
function apiError(int $code, string $msg, array $data = [], array $trace = [])
{
    $res = [
        'code' => $code,
        'msg'  => $msg,
    ];
    if ($data) {
        $res['data'] = $data;
    }
    if ($trace) {
        $res['trace'] = $trace;
    }
    return $res;
}

/**
 * 编辑env文件
 */
if(!function_exists('modifyEnv')){
    function modifyEnv(array $data)
    {
        $envPath = base_path() . DIRECTORY_SEPARATOR . '.env';
        $contentArray = file_get_contents($envPath, FILE_IGNORE_NEW_LINES);
        $contentArray = explode("\r\n",$contentArray);
        foreach ($data as $key=>$value){
            foreach ($contentArray as $k=>$config){
                if(str_contains($config,$key)){
                    $contentArray[$k] = "{$key} = $value";
                }
            }
        }
        $content = join("\r\n",$contentArray);
        file_put_contents($envPath, $content);
    }
}

// 对ip地址进行查询
if(!function_exists('ipFind')) {
    function ipFind($ip, $isStr = true)
    {
        $ipArr = \support\utils\Ip::find($ip);
        if(is_array($ipArr)){
            $ipArr = array_filter($ipArr);
            $ipArr = array_unique($ipArr);
        }

        if ($ipArr && is_array($ipArr)) {
            return join(',', $ipArr);
        } else {
            return $ipArr;
        }
    }
}


if(!function_exists('getLogSize')) {
    //获取指定位置日志文件大小
    function getLogSize()
    {
        $file_size = 0;//日志大小
        $file_count = 0;//日志文件树
        $log_path = base_path() . '/runtime/logs/err/';
        $info = getFolders($log_path, 'log');
        $file_size += $info['size'];
        $file_count += $info['count'];
        return ['size' => $file_size, 'count' => $file_count];
    }
}

//文本取中间
if(!function_exists('getSubstr')) {
    function getSubstr($str, $leftStr, $rightStr)
    {
        $left = strpos($str, $leftStr);
        if ($left === false) return '';
        $right = strpos($str, $rightStr, $left + strlen($leftStr));
        if ($right === false) return '';
        if ($left < 0 or $right < $left) return '';
        return substr($str, $left + strlen($leftStr), $right - $left - strlen($leftStr));
    }
}

if(!function_exists('mkdirs')) {
//递归循环创建目录
    function mkdirs($dir, $mode = 0777)
    {
        if (!is_dir($dir)) {
            mkdirs(dirname($dir), $mode);
            return mkdir($dir, $mode);
        }
        return true;
    }
}


//计算指定目录的文件大小
 function getFolders($file_path,$pattern='php'){
    $file_size = 0;//日志大小
    $file_count = 0;//日志文件树
    foreach (list_file($file_path) as $f){
        if($f['isDir']){
            $info = getFolders($f['pathname'].'/',$pattern);
            $file_size+=$info['size'];
            $file_count+=$info['count'];
        }else if($f['isFile'] && $f['ext']==$pattern){
            $file_size+=$f['size'];
            $file_count++;
        }
    }
    return ['size'=>$file_size,'count'=>$file_count];
}

/**
 * 列出本地目录的文件
 * @author rainfer <81818832@qq.com>
 * @param string $path
 * @param string $pattern
 * @return array
 */
function list_file($path, $pattern = '*')
{
    if (strpos($pattern, '|') !== false) {
        $patterns = explode('|', $pattern);
    } else {
        $patterns [0] = $pattern;
    }
    $i = 0;
    $dir = array();
    if (is_dir($path)) {
        $path = rtrim($path, '/') . '/';
    }
    foreach ($patterns as $pattern) {
        $list = glob($path . $pattern);
        if ($list !== false) {
            foreach ($list as $file) {
                $dir [$i] ['filename'] = basename($file);
                $dir [$i] ['path'] = dirname($file);
                $dir [$i] ['pathname'] = realpath($file);
                $dir [$i] ['owner'] = fileowner($file);
                $dir [$i] ['perms'] = substr(base_convert(fileperms($file), 10, 8), -4);
                $dir [$i] ['atime'] = fileatime($file);
                $dir [$i] ['ctime'] = filectime($file);
                $dir [$i] ['mtime'] = filemtime($file);
                $dir [$i] ['size'] = filesize($file);
                $dir [$i] ['type'] = filetype($file);
                $dir [$i] ['ext'] = is_file($file) ? strtolower(substr(strrchr(basename($file), '.'), 1)) : '';
                $dir [$i] ['isDir'] = is_dir($file);
                $dir [$i] ['isFile'] = is_file($file);
                $dir [$i] ['isLink'] = is_link($file);
                $dir [$i] ['isReadable'] = is_readable($file);
                $dir [$i] ['isWritable'] = is_writable($file);
                $i++;
            }
        }
    }
//    $cmp_func = create_function('$a,$b', '
//		if( ($a["isDir"] && $b["isDir"]) || (!$a["isDir"] && !$b["isDir"]) ){
//			return  $a["filename"]>$b["filename"]?1:-1;
//		}else{
//			if($a["isDir"]){
//				return -1;
//			}else if($b["isDir"]){
//				return 1;
//			}
//			if($a["filename"]  ==  $b["filename"])  return  0;
//			return  $a["filename"]>$b["filename"]?-1:1;
//		}
//		');
    usort($dir, function($a,$b){
        if( ($a["isDir"] && $b["isDir"]) || (!$a["isDir"] && !$b["isDir"]) ){
            return  $a["filename"]>$b["filename"]?1:-1;
        }else{
            if($a["isDir"]){
                return -1;
            }else if($b["isDir"]){
                return 1;
            }
            if($a["filename"]  ==  $b["filename"])  return  0;
            return  $a["filename"]>$b["filename"]?-1:1;
        }
    });
    return $dir;
}


/**
 * curl HTTP请求
 * @param  [type]  $url      网址
 * @param  string $opt 提交参数
 * @param  [type]  &$header  取回的头信息
 * @param  boolean $redirect 是否重定向
 * @param  boolean $ssl 验证https证书
 * @return [type]            返回信息
 */
function httpRequest($url, $opt = 'GET', &$code = null, &$header = null, $redirect = true, $ssl = false)
{
    //初始化
    $ch = curl_init($url);
    //配置设置
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $ssl);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, $ssl);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, $redirect);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                 #返回结果
    curl_setopt($ch, CURLOPT_HEADER, true);                         #显示头信息
    curl_setopt($ch,CURLOPT_TIMEOUT,3);//设置限制超时时间
    // curl_setopt($ch, CURLOPT_ENCODING ,'gzip');
    if (is_array($opt)) {
        //转小写
        $opt = array_change_key_case($opt, CASE_LOWER);
        if (isset($opt['type']) && strtoupper($opt['type']) == 'POST') {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, (isset($opt['data']) ? $opt['data'] : ''));
        }
        if (array_key_exists('ua', $opt))
            curl_setopt($ch, CURLOPT_USERAGENT, $opt['ua']);
        if (array_key_exists('header', $opt)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, (array)$opt['header']);
        }
        if (array_key_exists('cookie', $opt))
            curl_setopt($ch, CURLOPT_COOKIE, $opt['cookie']);
        if (array_key_exists('referer', $opt))
            curl_setopt($ch, CURLOPT_REFERER, $opt['referer']);
    } else {
        if (strtoupper((string)$opt) == 'POST')
            curl_setopt($ch, CURLOPT_POST, true);
    }
    $result = curl_exec($ch);
    if (curl_errno($ch)) {
        $result = curl_error($ch);
    } else {
        $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $length = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
        $header = substr($result, 0, $length);

        $result = substr($result, $length);
    }
    //释放
    curl_close($ch);
    return $result;
}


/**
 * 返回当前登陆的adminID
 * @return int|mixed
 */
function getAdminId(){
    $session = session();
    $admin = $session->get('admin');
    return  $admin['id']?:0;
}

if(!function_exists('tuActionLog')){
    function tuActionLog(Webman\Http\Request $request,$actName,$type=1){
        $installData = [
            'type'=>$type,
            'admin_id'=>getAdminId(),
            'url'=>$request->uri(),
            'name'=>$actName,
            'params'=>$request->all(),
            'ip'=>$request->getRealIp(),
            'create_at'=>date('Y-m-d H:i:s'),
        ];
        \app\admin\app\model\ActionLog::create($installData);
    }
}

/**
 * 二维数组根据某个字段排序
 * @param array $array 要排序的数组
 * @param string $keys   要排序的键字段
 * @param string $sort  排序类型  SORT_ASC     SORT_DESC
 * @return array 排序后的数组
 */
function arraySort($array, $keys, $sort = SORT_DESC) {
    $keysValue = [];
    foreach ($array as $k => $v) {
        $keysValue[$k] = $v[$keys];
    }
    array_multisort($keysValue, $sort, $array);
    return $array;
}

/**
 * 随机字符
 * @param int $length 长度
 * @param string $type 类型
 * @param int $convert 转换大小写 1大写 0小写
 * @return string
 */
function random($length = 10, $type = 'letter', $convert = 0)
{
    $config = array(
        'number' => '1234567890',
        'letter' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
        'string' => 'abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789',
        'all' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
    );

    if (!isset($config[$type])) $type = 'letter';
    $string = $config[$type];

    $code = '';
    $strlen = strlen($string) - 1;
    for ($i = 0; $i < $length; $i++) {
        $code .= $string[mt_rand(0, $strlen)];
    }
    if (!empty($convert)) {
        $code = ($convert > 0) ? strtoupper($code) : strtolower($code);
    }
    return $code;
}

//function dump($trage){
//    /**
//     * 打印数组或字符串
//     */
//    $str = is_array($trage) ? var_export($trage,1) : trim($trage);
//    throw new \support\exception\DumpException($str);
//}